package com.cmcc.driver.ui.main

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.cmcc.driver.R
import com.cmcc.driver.config.DriverPath
import com.cmcc.driver.data.entity.Order
import com.cmcc.driver.databinding.FragmentOrderRecordBinding
import com.cmcc.driver.ui.main.adapter.MyOrderItemClickListener
import com.cmcc.driver.ui.main.adapter.OrderRecordAdapter
import com.cmcc.driver.ui.main.viewmodel.OrderRecordViewModel
import com.cmcc.shared.adapter.SpaceItemDecoration
import com.cmcc.shared.utils.DisplayUtil

/**
 * Author: jiangxin
 * Date: 2019/11/5
 * Description:
 */
class OrderRecordFragment : Fragment() {

    private lateinit var viewModel: OrderRecordViewModel
    private lateinit var binding: FragmentOrderRecordBinding
    private var adapter: OrderRecordAdapter? = null

    private var lastPage: Int = 0
    private var currentPage: Int = 1
    private val pageSize = 10
    private var lastVisibleItemPosition: Int = -1

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentOrderRecordBinding.inflate(inflater, container, false)
        binding.recyclerView.layoutManager = LinearLayoutManager(activity)
        binding.recyclerView.addItemDecoration(
            SpaceItemDecoration(
                DisplayUtil.dp2px(
                    context!!,
                    20f
                ).toInt()
            )
        )
        adapter = OrderRecordAdapter()
        adapter?.addItemClickListener(onItemClickListener())
        binding.recyclerView.adapter = adapter
        viewModel = ViewModelProviders.of(this).get(OrderRecordViewModel::class.java)

        updateUI()
        binding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                val layoutManager = recyclerView.layoutManager
                if (layoutManager is LinearLayoutManager) {
                    lastVisibleItemPosition =
                        layoutManager.findLastVisibleItemPosition()
                }
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                    && lastVisibleItemPosition + 1 == recyclerView.adapter?.itemCount
                ) {
                    if (currentPage > lastPage)
                        viewModel.getRecords(currentPage, pageSize)
                }

            }
        })

        binding.swipeRefreshLayout.setColorSchemeColors(resources.getColor(R.color.driver_colorAccents))
        binding.swipeRefreshLayout.setOnRefreshListener {
            updateUI()
        }

        viewModel.records.observe(this, Observer { records ->
            binding.swipeRefreshLayout.isRefreshing = false
            lastPage = currentPage
            if (currentPage == 1) {
                adapter?.removeList()
            }
            if (currentPage <= records.pages) {
                adapter?.addList(records.list)
                currentPage++
            }
            adapter?.notifyDataSetChanged()

            if (adapter?.itemCount == 0) {
                binding.noRecordLayout.visibility = View.VISIBLE
            } else {
                binding.noRecordLayout.visibility = View.GONE
            }
        })

        return binding.root
    }

    fun updateUI() {
        currentPage = 1
        viewModel?.getRecords(currentPage, pageSize)
    }

    var mLastClickTime: Long = 0
    val TIME_INTERVAL = 1000L

    private fun onItemClickListener(): MyOrderItemClickListener {
        return object : MyOrderItemClickListener {
            override fun click(
                binding: View,
                model: Order
            ) {
                val nowTime = System.currentTimeMillis()
                if (nowTime - mLastClickTime > TIME_INTERVAL) {
                    mLastClickTime = nowTime
                    ARouter.getInstance().build(DriverPath.ORDER_RECORD_DETAIL)
                        .withString("orderId",model.id)
                        .navigation()
                }
            }
        }
    }
}